using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using ORS.OrderRobot.Cache;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;

namespace ORS.OrderRobot.Service;

public class SystemConfigService : ISystemConfigService,ISingleton
{
    private readonly ICache _cache;
    private readonly IMapper _mapper;
    private readonly IServiceProvider _serviceProvider;
    public SystemConfigService(
        ICache cache,
        IMapper mapper,
        IServiceProvider serviceProvider)
    {
        _cache = cache;
        _mapper = mapper;
        _serviceProvider = serviceProvider;
    }
    public async Task<SystemConfigDto> GetConfigAsync()
    {
        using var scope = _serviceProvider.CreateScope();
        var _systemConfigRepository = scope.ServiceProvider.GetRequiredService<IRepository<SystemConfig, int>>();

        var cacheObj = await _cache.GetAsync<SystemConfigDto>(Consts.CacheKey.SystemConfig);
        if(cacheObj == null)
        {
            var entity = (await _systemConfigRepository.GetListAsync()).FirstOrDefault();
            if (entity == null)
            {
                entity = new SystemConfig();
                await _systemConfigRepository.InsertAsync(entity);
            }
            cacheObj = _mapper.Map<SystemConfigDto>(entity);
            await _cache.SetAsync(Consts.CacheKey.SystemConfig, cacheObj);
        }
        return cacheObj;
    }

    public async Task SetConfigAsync(SystemConfigDto input)
    {
        using var scope = _serviceProvider.CreateScope();
        var _systemConfigRepository = scope.ServiceProvider.GetRequiredService<IRepository<SystemConfig, int>>();
        // 获取现有的系统配置
        var entity = (await _systemConfigRepository.GetListAsync(tracking:true)).FirstOrDefault();
        
        if (entity == null)
        {
            // 如果不存在，创建新的配置
            entity = _mapper.Map<SystemConfig>(input);
            entity.LatestUpdateTime = DateTime.Now.China();
            await _systemConfigRepository.InsertAsync(entity);
        }
        else
        {
            // 如果存在，更新现有配置
            _mapper.Map(input, entity);
            entity.LatestUpdateTime = DateTime.Now.China();
            await _systemConfigRepository.UpdateAsync(entity);
        }
        
        // 清除缓存，确保下次获取时能拿到最新数据
        await _cache.SetAsync(Consts.CacheKey.SystemConfig, input);
    }
}